import { createStore } from 'vuex';

// 初始化时从localStorage加载用户数据
const savedUser = localStorage.getItem('badmintonUser');
const initialUser = savedUser ? JSON.parse(savedUser) : null;

// 加载社区帖子数据
const savedPosts = localStorage.getItem('communityPosts');
const initialPosts = savedPosts ? JSON.parse(savedPosts) : [];

// 加载二手交易数据
const savedSecondHandItems = localStorage.getItem('secondHandItems');
const initialSecondHandItems = savedSecondHandItems ? JSON.parse(savedSecondHandItems) : [];

export default createStore({
  state: {
    user: initialUser,
    communityPosts: initialPosts,
    secondHandItems: initialSecondHandItems
  },
  mutations: {
    // 用户登录
    login(state, userData) {
      state.user = userData;
      localStorage.setItem('badmintonUser', JSON.stringify(userData));
    },
    // 用户登出
    logout(state) {
      state.user = null;
      localStorage.removeItem('badmintonUser');
    },
    // 注册新用户
    register(state, userData) {
      state.user = userData;
      localStorage.setItem('badmintonUser', JSON.stringify(userData));
    },
    // 添加社区帖子
    addCommunityPost(state, post) {
      state.communityPosts.push(post);
      localStorage.setItem('communityPosts', JSON.stringify(state.communityPosts));
    },
    // 添加二手交易物品
    addSecondHandItem(state, item) {
      state.secondHandItems.push(item);
      localStorage.setItem('secondHandItems', JSON.stringify(state.secondHandItems));
    }
  },
  actions: {
    // 异步登录操作
    login({ commit }, userData) {
      commit('login', userData);
    },
    // 异步登出操作
    logout({ commit }) {
      commit('logout');
    },
    // 异步注册操作
    register({ commit }, userData) {
      commit('register', userData);
    },
    // 发布社区帖子
    publishCommunityPost({ commit }, post) {
      const postWithId = {
        ...post,
        id: Date.now(),
        createdAt: new Date().toISOString()
      };
      commit('addCommunityPost', postWithId);
    },
    // 发布二手交易物品
    publishSecondHandItem({ commit }, item) {
      const itemWithId = {
        ...item,
        id: Date.now(),
        createdAt: new Date().toISOString()
      };
      commit('addSecondHandItem', itemWithId);
    }
  },
  getters: {
    isLoggedIn(state) {
      return !!state.user;
    },
    currentUser(state) {
      return state.user;
    },
    allCommunityPosts(state) {
      return [...state.communityPosts].reverse();
    },
    allSecondHandItems(state) {
      return [...state.secondHandItems].reverse();
    }
  }
});